package com.xymc.webmgr.config.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * <p>mysql数据源<p>
 *
 * @Version : 1.0
 * @Author : lihao
 * @Description :mysql的数据源
 * 这里我们定义的数据源要扫描mysql对应的mapper.java包和mapper.xml目录
 * @Date : 2021/10/27 14:38
 **/
@Configuration
@MapperScan(basePackages = MyBatisConfigdb1.PACKAGE,sqlSessionFactoryRef = "db1SqlSessionFactory")
public class MyBatisConfigdb1 {

    // 精确到 db1 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.xymc.webmgr.dao.db1";
    static final String MAPPER_LOCATION = "classpath:mappers/db1/*.xml";

    @Value("${spring.datasource.db1.url}")
    private String url;

    @Value("${spring.datasource.db1.username}")
    private String user;

    @Value("${spring.datasource.db1.password}")
    private String password;

//    @Value("${spring.datasource.db1.driverClassName}")
//    private String driverClass;

    @Bean(name = "db1DataSource")
    @Primary
    public DataSource db1DataSource() {
        DruidDataSource dataSource = new DruidDataSource();
//        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager db1TransactionManager() {
        return new DataSourceTransactionManager(db1DataSource());
    }

    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource db1DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(db1DataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MyBatisConfigdb1.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

}
